<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<script th:inline="javascript">
// 支持分页功能后，此方法仅用于编辑、删除嵌套表记录及模块添加时拉单、编辑操作
function callCalculateOnload() {
	// 更新对嵌套表的列进行sum操作的控件
 	$("input[kind='CALCULATOR']").each(function(){
        var calObj = $(this);
        if ($(this).attr('formula')) {
           	var formula = $(this).attr('formula');
			var formCode = $(this).attr('formCode');
			var digit = $(this).attr('digit');
			var isRoundTo5 = $(this).attr('isRoundTo5');

           var isSum = false;
           var regStr = /(sum\(([\w|\.]+)\))/gi;
           var mactches = formula.match(regStr)
           var len = 0;
           if (mactches) {
           		len = mactches.length;
                isSum = true;
           }
           if (isSum) {
           	   // 累加列
               var field = RegExp.$2;
               if (field.indexOf("nest.")==0) {
               		var p = field.indexOf(".");
					// 取得列名
                    field = field.substring(p+1);
                    var sumField = $(this);
                    var v = 0;
                    // 遍历所有的嵌套表格2，对匹配到的列求和
					var $nestTable;
					if (formCode != null) {
						$nestTable = $("[id^=cwsNestTable_][formCode=" + formCode + "]");
					}
					else {
						$nestTable = $("[id^=cwsNestTable_]");
					}
					$nestTable.each(function() {
                    	v = 0;
                        var obj = $(this)[0]; // table
                        var rows = obj.rows.length;
                        var colIndex = getCellIndexByFieldNameOfNestSheet(obj, field);
                        if (colIndex!=-1) {
                            // alert(colIndex + " " + field);
                            for (var i=1; i < rows; i++) {
                                var cellV = getCellValueOfNestSheet(obj, i, colIndex).trim();
                                if (cellV!="") {
                                    if (!isNaN(cellV))
                                        v += eval(cellV);
                                }
                            }
                        }
                        else {
                        	// 页面没有全部加载完成时，可能会报不存在
							console.log("算式" + formula + "中 " + field + " 不存在！");
                            return; // 以免误算nesttable中的累加列
                        }
                        try  {
							// v = v.toFixed(2);
							if (isRoundTo5 != null && isRoundTo5 == 1){
								var digitNum = parseFloat(digit);
								if (!isNaN(digitNum)){
									v = v.toFixed(digitNum);
								}
							}
							else if(isRoundTo5 != null && isRoundTo5 == 0){
								var digitNum = parseFloat(digit);
								if (!isNaN(digitNum)) {
									v = v.toFixed(digitNum + 1);
									v = changeTwoDecimal_f(v, digitNum);
								}
							}
                        }
                        catch (e) {}
                        sumField.val(v);
                    });
               }
           }
		}
	});
}

var op = [[${op}]];
var isTab = [(${isTab})];
// i从1开始
[# th:if="${op eq 'forRefresh'}"]
	var $nestSheetContainerObj_[(${nestFormCode})]_[(${fieldName})] = $("#nestsheet_[(${fieldName})]");
	// 如果是智能模块添加页面，则重新加载newIds中的记录，否则刷新后显示第一页
	async function refreshNestSheetCtl(nestFieldName, newIds) {
		// var path = [[${path}]];
		console.log('refreshNestSheetCtl nestFieldName', nestFieldName, 'newIds', newIds, $('#cwsNestTable_' + nestFieldName)[0]);
		var path = $('#cwsNestTable_' + nestFieldName).attr('url');
		console.log('refreshNestSheetCtl path', path);
		path = (path.indexOf("?")!=-1)? path += "&"+new Date().getTime() : path += "?"+new Date().getTime()

		// 去除path中可能含有的newIds，以免造成重复
		var p = path.indexOf('newIds=');
		if (p != -1) {
			var q = path.indexOf('&', p + 'newIds='.length);
			path = path.substring(0, p) + path.substring(q);
		}
		console.log('refreshNestSheetCtl path2', path);

		var strNewIds = "";
		if (newIds!=null) {
			strNewIds = newIds;
		}

		console.log('refreshNestSheetCtl newIds', newIds, 'path', path);
		var data = await ajaxGet(path, {newIds: strNewIds});
		// console.log('data', data);
		if (isTab==0) {
			// 如果选项卡在刷新中途切换，如开工切换至注册评审，就会造成找不到$("#nestsheet_"+fieldName)无法刷新的情况
			$("#nestsheet_" + nestFieldName).html(data);

			initFormCtl([[${formName}]]);

			// 初始化日期控件
			initDatePicker();

			// $nestSheetContainerObj_[(${nestFormCode})]_[(${fieldName})].html(data);
			// console.log('#nestsheet_' + fieldName, $("#nestsheet_"+fieldName)[0]);
		}else{
			// 流程中选项卡式显示方式
			// $("#tabs-<%=nestFormCode %>").html(data);
		}
		// callCalculateOnload();
		try {
			onNestSheetRefresh(nestFieldName);
		} catch (e) {}
	}

	function initNestSheetAutoSel(nestFormCode, nestFieldName, flowId, formName, isAutoSel,
								  mainFormFieldNames, parentFormCode, mainId, pageType) {
		// 自动拉单
		console.log('macro_js_nestsheet isAutoSel', isAutoSel);
		if (isAutoSel) {	//如果是自动嵌套拉单，每隔两秒执行检查是否该刷新表格
			var fields = mainFormFieldNames;
			console.log('isAutoSel fields', fields);
			var fieldNames = fields.split(",");

			var fieldObj = fo(fieldNames[0], formName);

			var oldValueArr = getFormValue(fieldNames, formName);
			var ajaxData = {
				'flowId': flowId,
				'parentFormCode': parentFormCode,
				'parentId': mainId,
				'nestFieldName': nestFieldName,
				'isFirst': true
			};
			// 当找不到元素时oldValueArr为null，有可能是发起流程然后切换选项卡太快时，就会找不到
			if (oldValueArr != null) {
				for (var i in fieldNames) {
					ajaxData[fieldNames[i]] = oldValueArr[i];
				}
			}
			// 如果获取到值的数组中有不为空的，则需立即自动拉单，否则不需要
			var isDoAutoSelImmediate = false;
			if (oldValueArr != null && oldValueArr.length > 0) {
				for (var m in oldValueArr) {
					if (oldValueArr[m]) {
						isDoAutoSelImmediate = true;
						break;
					}
				}
			}
			console.log('oldValueArr', oldValueArr, 'isDoAutoSelImmediate', isDoAutoSelImmediate, 'pageType', pageType);

			// 如果是模块编辑，则不需要自动拉单，否则拉单后将清除原来的数据
			/*if ("edit" == pageType) {
				if (isDoAutoSelImmediate) {
					doAutoSel(nestFormCode, ajaxData, nestFieldName, flowId, formName);
				}
			}*/

			// 配置了条件,没有配置条件则不处理
			if (fields != '') {
				// 500毫秒以后开始检查，此处得优化，否则在编辑时，可能会自动拉单
				setTimeout(function() {
					// 100毫秒检测一次
					var sint = window.setInterval(function() {
						if (o(formName)) {
							var newValueArr = getFormValue(fieldNames, formName);
							if (newValueArr != null && oldValueArr != null) {
								if(JSON.stringify(oldValueArr) != JSON.stringify(newValueArr)) {
									console.log('oldValueArr', oldValueArr, 'newValueArr', newValueArr, 'nestFieldName', nestFieldName);
									oldValueArr = newValueArr;
									var ajaxData = {
										'flowId': flowId,
										'parentFormCode': parentFormCode,
										'parentId': mainId,
										'nestFieldName': nestFieldName,
										'isFirst':false
									};
									var isAllEmpty = true;
									for (var i in fieldNames) {
										ajaxData[fieldNames[i]] = newValueArr[i];
										if (newValueArr[i]) {
											isAllEmpty = false;
										}
									}
									// 如果全部参数都为空，则不能自动拉单
									if (!isAllEmpty) {
										doAutoSel(nestFormCode, ajaxData, nestFieldName, flowId, formName);
									}
								}
							}
						}
					}, 100);

					try {
						cwsGlobalAutoSelIntervalArr.push(sint);
						console.log('cwsGlobalAutoSelIntervalArr', cwsGlobalAutoSelIntervalArr);
					} catch (e) {
						console.warn('cwsGlobalAutoSelIntervalArr is not defined.');
					}
					getCurFormUtil().addInterval(sint, formName);
				}, 500);
			}
		}
	}

	console.log('isAutoSel', '[(${isAutoSel})]');
	// 用于在processHandleView中判断在保存草稿后是否刷新界面，如果刷新，会导致重新自动拉单，而致修改的数据丢失
	// var hasAutoSelFieldInForm = '[(${isAutoSel})]';

	initNestSheetAutoSel('[(${nestFormCode})]', '[(${nestFieldName})]', [(${flowId})], '[(${formName})]', [(${isAutoSel})],
			'[(${mainFormFieldNames})]', '[(${parentFormCode})]', '[(${mainId})]', '[(${pageType})]');

	async function doAutoSel(nestFormCode, ajaxData, nestFieldName, flowId, formName) {
		var data = await ajaxPost('/nestsheetctl/autoSel', ajaxData);
		console.log('autoSel data', data, 'nestFieldName', nestFieldName);
		if (data.ret == '1') {
			var newIds = data.newIds;
			if (newIds==null) {
				newIds = "";
			}

			await refreshNestSheetCtl(nestFieldName, newIds);

			callCalculateOnload();

			if (flowId == -1) {
				if (newIds!="") {
					// 清除之前拉单的结果，因为有可能是更改了条件字段的值，重新拉单
					$("input[name='tempCwsId_" + nestFieldName + "']").remove();

					var idsAry = newIds.split(",");
					for (x in idsAry) {
						addTempCwsId("[(${nestFormCode})]", idsAry[x], formName, nestFieldName);
					}
				}
			}
			eventTarget.fireEvent({
				type: EVENT_TYPE.NEST_AUTO_SEL_DONE,
				moduleCode: nestFormCode,
				newIds: newIds
			});
		}
	}

	// 获取主表单中的值并拼接成sql的where字句
	function getFormValue(fieldNames, formName){
		var arr = new Array();
		for(var i = 0;i < fieldNames.length;i++) {
			var obj = findObjInForm(formName, fieldNames[i]);
			if (obj) {
				arr[i] = obj.value;
			} else {
				console.warn('getFormValue 表单中未找到: ' + fieldNames[i]);
				return null;
			}
		}
		return arr;
	}
[/]
function getCellValueOfNestSheet(tableObj, i, j) {
	var cel = tableObj.rows.item(i).cells;
	var fieldType = tableObj.rows[0].cells[j].getAttribute("type");
	var macroType = tableObj.rows[0].cells[j].getAttribute("macroType");

	// 标值控件
	if (macroType=="macro_raty") {
		if(cel[j].children[0] && cel[j].children[0].tagName=="SPAN") {
			var ch = cel[j].children[0].children;
			for (var k=0; k < ch.length; k++) {
				if (ch[k].tagName=="INPUT") {
					return ch[k].value;
				}
			}
		}
	}
	// 在clear_color时，会置宏控件所在单元格的value属性为控件的值
	else if (cel[j].getAttribute("value")) {
		return cel[j].getAttribute("value");
	}
	else {
		if (cel[j].children.length>0) {
			var cellDiv = cel[j].children[0];
			return cellDiv.innerText.trim();
		}
		else {
			return cel[j].innerText.trim();
		}
	}
	return "";
}

// 区别于nest_table_view.jsp中的方法，以免重复
function getCellIndexOfNestSheet(td){
    if (isIE()){
        var cells=td.parentNode.cells;
        for (var i=0,j=cells.length;i < j;i++ ){
            if (cells[i]===td){
                return i;
            }
        }
    }
    return td.cellIndex;
}

function getCellIndexByFieldNameOfNestSheet(tableObj, fieldName) {
	for(var i=0; i < tableObj.rows[0].cells.length; i++){
		if (tableObj.rows[0].cells[i].getAttribute("fieldName")==fieldName)
			return i;
	}
	return -1;
}

function hideNestSheetCol(fieldName) {
    $("[id^=cwsNestTable_]").each(function() {
        var obj = $(this)[0]; // table
        var rowsLen = obj.rows.length;
        var colIndex = getCellIndexByFieldNameOfNestSheet(obj, fieldName);
    	if (colIndex!=-1) {
            for (var i=0; i < rowsLen; i++) {
                obj.rows[i].cells[colIndex].style.display = "none";
            }
        }
    });
}
</script>
</body>
</html>